import VueCookie from 'vue-cookie'
import AppConstant from '@/constant/app-constant'
import store from '@/store'
import { containsAll } from '@/utils'
import ApiUrl from "@/constant/api-url";
import { getCurrHost } from "./index";

export function getToken () {
  return VueCookie.get(AppConstant.COOKIE_KEY_TOKEN)
}

export function getLang () {
  return VueCookie.get(AppConstant.COOKIE_KEY_LANG)
}

export function getIsMultipleIp () {
  return VueCookie.get(AppConstant.COOKIE_KEY_IS_MULTIPLE_IP)
}

export function setToken (token, isRememberMe) {
  if (isRememberMe) {
    return VueCookie.set(AppConstant.COOKIE_KEY_TOKEN, token, 7)
  } else {
    return VueCookie.set(AppConstant.COOKIE_KEY_TOKEN, token)
  }
}

export function removeToken () {
  return VueCookie.delete(AppConstant.COOKIE_KEY_TOKEN)
}

/**
 * 是否有权限
 *
 * @param {Array} needAuthorizations 需要的权限
 * @param {int} logical 1：and（与，默认，所有权限都需要满足）2：or（或，有一条权限满足就可以）
 * @returns {*}
 */
export function hasPermission (needAuthorizations, logical = 1) {
  if (!needAuthorizations || needAuthorizations.length === 0) {
    return true
  }
  let hasAuthorizations = store.getters.authorizations
  if (!hasAuthorizations || hasAuthorizations.length === 0) {
    return false
  }
  if (logical === 1) {
    return containsAll(hasAuthorizations, needAuthorizations)
  } else if (logical === 2) {
    return needAuthorizations.some(function (item) {
      return hasAuthorizations.indexOf(item) > -1
    })
  }
  return false
}

/**
 * 跳转到sso登录页
 */
export function goSsoLogin ({needBack = true, backUrl} = {}) {
  // 对backUrl进行编码，防止后台获取不完整的路径
  let encodeUrl = ''
  if (needBack && backUrl !== '' && backUrl) {
    encodeUrl = encodeURIComponent(backUrl)
  }
  let host = getCurrHost()
  // 通过服务端处理跳转sso login
  let fullLoginUrl = ApiUrl.API_HOST_BASE + ApiUrl.SSO_LINK_URL_GO_SSO_LOGIN + '?' + 'host=' + host +
      (needBack ? '&' + ApiUrl.APP_URL_KEY_BACK_URL + '=' + encodeUrl : '')
  window.location.href = fullLoginUrl
}

/**
 * 跳转到sso首页
 */
export function goSsoHome () {
  let host = getCurrHost()
  window.location.href = ApiUrl.API_HOST_BASE + ApiUrl.SSO_LINK_URL_GO_SSO_HOME + '?' + 'host=' + host
}

/**
 * 获取登录设置相关 传参数this
 */
// 登录名称
export function getLoginName (that) {
  return that.$store.getters.loginName
}

// 登录风格
export function getLoginStyle (that) {
  return that.$store.getters.loginStyle
}

// logo
export function getBase64Logo (that) {
  return that.$store.getters.base64Logo
}

// 登录后icon
export function getBase64Icon (that) {
  return that.$store.getters.base64Icon
}

// 标签页icon
export function getBase64TopbarIcon (that) {
  return that.$store.getters.base64TopbarIcon
}
